﻿using AutoMapper;
using B.S.BaseData.Domain;
using B.S.BaseData.ErrorCode;
using B.S.BaseData.Read.Api.Application.Command;
using B.S.BaseData.Read.Api.Dtos;
using MediatR;
using SqlSugar;

namespace B.S.BaseData.Read.Api.Application.CommandHander
{
    public class GetMenuCommandHander : IRequestHandler<GetMenuCommand, ApiResult<List<GetMenuDto>>>
    {

        private readonly IMapper mapper;
        private readonly ISqlSugarClient db;

        public GetMenuCommandHander(IMapper mapper, ISqlSugarClient db)
        {
            this.mapper = mapper;
            this.db = db;
        }


        /// <summary>
        /// 显示菜单处理
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public Task<ApiResult<List<GetMenuDto>>> Handle(GetMenuCommand request, CancellationToken cancellationToken)
        {
            ApiResult<List<GetMenuDto>> result = new ApiResult<List<GetMenuDto>>();

            result.Code = ApiEnum.显示成功;
            result.Msg = ApiEnum.显示成功.ToString();

            var linq = db.Queryable<Menu>()
                .InnerJoin<User>((menu, user) => menu.CreateBy == user.UserId)
                .Select((menu, user) => new GetMenuDto
                {
                    Id = menu.Id,
                    MenuName = menu.MenuName,
                    Url = menu.Url,
                    PId = menu.PId,
                    CreateBy = menu.CreateBy,
                    CreateDate = menu.CreateDate,
                    UpdateBy = menu.UpdateBy,
                    UpdateDate = menu.UpdateDate,
                    UserName = user.UserName
                });

            var entity = linq.OrderBy(menu => menu.Id).ToList();

            result.Data = mapper.Map<List<GetMenuDto>>(entity);

            return Task.FromResult(result);
        }
    }
}
